import requests
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import *
from .tool import mail, get_name, make_jwt
from random import randint
import redis
from django.contrib.auth.hashers import make_password, check_password
from rest_framework_jwt.serializers import jwt_payload_handler,jwt_encode_handler
r = redis.Redis(host='localhost', port=6379, decode_responses=True)


def connectredis():
    pool = redis.ConnectionPool(host="Localhost", port=6379, decode_response=True)
    return redis.Redis(connection_pool=pool)


# 发送邮件
class LouView(APIView):
    def post(self, request):
        # 接收参数
        username = request.data.get('username')
        type = request.data.get('type')
        user = User.objects.filter(username=username)
        code = str(randint(1000, 100000))
        # 查询邮箱是否可用
        if int(type == 1):
            if user:
                return Response({'code': 201, 'message': '邮箱不可用或已被注册'})

            # 发送邮件验证码
            try:
                content = '您正在注册实验楼，验证码' + code + '有效期5分钟'
                subject = '【注册账号】'
                mail.delay(subject, content, username)

                # 存入redis
                r.setex(username, 300, code)
                return Response(200)

            except Exception as e:
                print(e)
                return Response(400)

            # 发送邮箱验证码
        try:
            code = str(randint(1000, 100000))
            content = '您正在修改免密，验证码为' + code + '有效期5分钟,请勿泄露'
            subject = '【邮箱验证】'
            mail.delay(subject, content, username)

            # 存入redis
            r.setex(username, 600, code)
            return Response(200)
        except Exception as e:
            print(e)
            return Response(400)


class Register(APIView):
    def post(self, request):

        username = request.data.get('username')
        password = request.data.get('password')
        print(password)
        code = request.data.get('code')
        redis_code = r.get(username)
        if code != redis_code:
            return Response(400)
        # 入库
        if username:
            user = User.objects.create(username=username, password=make_password(password), name=get_name())
            return Response(200)
        return Response(400)


class Login(APIView):
    def post(self, request):
        username = request.data['username']
        password = request.data['password']

        user = User.objects.filter(username=username).first()
        pwd = user.password
        if user and pwd == password:
            uid = user.id
            token = make_jwt(uid)
            print(token)

            return Response({'msg': "登陆成功"})
        else:
            return Response({'msg': "登陆失败"})


#  微博三方登陆接口
class WeiboView(APIView):
    def get(self, request):

        code = request.GET.get("code")  # 获取传递来的code
        # print(code)


        data = {
            "client_id": "4121380497",
            "client_secret": "707e076f7fb51084ec8158579e62ebd4",
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": "http://127.0.0.1:8080/jb",
        }

        r = requests.post("https://api.weibo.com/oauth2/access_token", data=data)

        uid = r.json()['uid']
        print(uid)
        suser = DiSan.objects.filter(uid=uid).first()

        if suser:
            # user = User.objects.get(id=suser.user_id_id)
            user = suser.user_id
            id = user.id
            name = user.username
            # jwt ->
            userobj = User.objects.filter(id=id).first()
            payload = jwt_payload_handler(userobj)
            token = jwt_encode_handler(payload)
            return Response({'code': 200, 'uid': uid, 'token': token})
        # 引导绑定
        return Response({'code': 10000,'uid':uid})

# 微博登陆绑定用户接口
class BindView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        uid = request.data.get('uid')
        print(uid)

        try:
            # user = User.objects.get(username=username, password=password).id
            # print(user)
            user = User.objects.create(username=username, password=password)
            DiSan.objects.create(uid=uid, user_id=user)
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            return Response({'msg': '绑定成功', 'token': token}, status=200)
        except Exception as e:
            print(e)
            return Response({'msg': '绑定失败'}, status=500)
